package com.longteng.diamond.service;


import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.longteng.diamond.dao.BuildTestMapper;
import com.longteng.diamond.dao.QuartzMapper;
import com.longteng.diamond.dao.TestCaseMapper;
import com.longteng.diamond.dao.TestPlanMapper;
import com.longteng.diamond.domain.*;
import com.longteng.diamond.po.RequestResult;
import com.longteng.diamond.po.TreeMenu;
import com.longteng.diamond.util.ReportLogFileUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator
 * DATE : 2018/6/28
 * TIME : 20:33
 * PROJECT : java-lesson
 * PACKAGE : com.longteng.lesson
 *
 * @author <a href="mailto:taki@qq.com">Administrator</a>
 */
@Slf4j
@Component
public class TestPlanService {
    @Autowired
    TestPlanMapper testPlanMapper;
    @Autowired
    TestCaseMapper testCaseMapper;
    @Autowired
    BuildTestMapper buildTestMapper;
    @Autowired
    TestCaseService testCaseService;
    @Autowired
    BuildTestService buildTestService;
    @Autowired
    QuartzService quartzService;
    @Autowired
    QuartzMapper quartzMapper;
    @Autowired
    IndexService indexService;
    @Value("${report.shareDir}")
    private String shareDir;

    /**
     * 根据项目id获取计划树
     *
     * @param projectId
     * @return Map
     */
    public List<TreeMenu> getTestPlanTree(Integer projectId) {
        TestPlan testPlan = new TestPlan();
        testPlan.setProjectId(projectId);
        List<TestPlan> testPlanList = testPlanMapper.getTestPlan(testPlan);
        List<TreeMenu> treeList = Lists.newArrayList();
        for (TestPlan testPlan1 : testPlanList) {
            TreeMenu planTree = new TreeMenu();
            planTree.setIconSkin("icon03");
            planTree.setName(testPlan1.getTestPlanName());
            planTree.setId(testPlan1.getTestPlanId());
            treeList.add(planTree);
        }
        return treeList;
    }

    /**
     * 根据项目id获取计划树
     *
     * @param testPlanId
     * @return Map
     */
    public TestPlan getTestPlanById(Integer testPlanId) {
        TestPlan testPlan = new TestPlan();
        testPlan.setTestPlanId(testPlanId);
        List<TestPlan> testPlanList = testPlanMapper.getTestPlan(testPlan);
        testPlan = testPlanList.get(0);
        List<TestPlanDetail> testPlanDetailList = testPlanMapper.findTestPlanDetailByTestPlanId(testPlan.getTestPlanId());
        testPlan.setTestPlanDetailList(testPlanDetailList);
        /**
         * 获取定时任务
         * **/
        ScheduleJob scheduleJob = new ScheduleJob();
        scheduleJob.setTestPlanId(testPlanId);
        List<ScheduleJob> scheduleJobList = quartzMapper.findQuartz(scheduleJob);
        if (!CollectionUtils.isEmpty(scheduleJobList)) {
            scheduleJob=scheduleJobList.get(0);
            testPlan.setHhTime(scheduleJob.getHhTime());
            testPlan.setMmTime(scheduleJob.getMmTime());
            testPlan.setWeekTimeList(scheduleJob.getWeekTimeList());
        }
        /**
         * 获取执行记录,为了测试计划画图
         * **/
        BuildTest buildTest = new BuildTest();
        buildTest.setTestPlanId(testPlanId);
        List<BuildTest> buildTestList = indexService.testPlanRunMetric(buildTest);
        if(!CollectionUtils.isEmpty(buildTestList)) {
            testPlan.setPlanBuildTestList(buildTestList);
        }
        /**
         * 获取最后一个构建,为了测试计划top显示
         * **/
        BuildTest buildTest1=new BuildTest();
        buildTest1.setTestPlanId(testPlanId);
        buildTest1.setSortString("startTime");
        buildTest1.setPageNo(0);
        buildTest1.setPageSize(1);
        List<BuildTest> buildTests=buildTestMapper.getBuildTest(buildTest1);
        if(!CollectionUtils.isEmpty(buildTests)) {
            testPlan.setLastBuildTest(buildTests.get(buildTests.size()-1));
        }
        return testPlan;
    }

    /**
     * 删除测试计划
     *
     * @param testPlanId
     * @return RequestResult
     */
    public void deleteTestPlan(Integer testPlanId) {
        testPlanMapper.deleteTestPlan(testPlanId);
    }

    /**
     * 获取最后一次新增的测试计划
     *
     * @param projectId
     * @return RequestResult
     */
    public TestPlan getLastPlan(Integer projectId) {
        TestPlan testPlan = new TestPlan();
        testPlan.setProjectId(projectId);
        testPlan.setPageNo(0);
        testPlan.setPageSize(1);
        testPlan.setSortString("testPlanId");
        List<TestPlan> testPlanList = testPlanMapper.getTestPlan(testPlan);
        if (CollectionUtils.isEmpty(testPlanList)) {
            return null;
        } else {
            testPlan = testPlanList.get(0);
        }
        testPlan= this.getTestPlanById(testPlan.getTestPlanId());
        return testPlan;
    }

    /**
     * 新增测试计划
     *
     * @param testCaseIds
     * @param testPlan
     * @return RequestResult
     */
    public void updateTestPlan(TestPlan testPlan, Integer[] testCaseIds) {
        testPlanMapper.updateTestPlan(testPlan);
        /**
         * 把原来的用例全部删除,重新添加,因为用例可能调整了,或者顺序变了,删除重新添加最简单
         * */
        testPlanMapper.deletePlanDetail(testPlan.getTestPlanId());
        Map map = Maps.newHashMap();
        map.put("testCaseIds", testCaseIds);
        map.put("testPlanId", testPlan.getTestPlanId());
        testPlanMapper.addPlanDetail(map);

        if (!StringUtils.isBlank(testPlan.getWeekTimeList())) {
            List list = JSON.parseObject(testPlan.getWeekTimeList(), List.class);
            if (!CollectionUtils.isEmpty(list)) {
                ScheduleJob scheduleJob = new ScheduleJob();
                BeanUtils.copyProperties(testPlan, scheduleJob);
                quartzService.modifyQuartzJob(scheduleJob);
            }
        }
    }

    /**
     * 新增测试计划
     *
     * @param testCaseIds
     * @param testPlan
     * @return RequestResult
     */
    @Transactional(rollbackFor = Exception.class)
    public void addTestPlan(TestPlan testPlan, Integer[] testCaseIds) {
        testPlanMapper.addPlan(testPlan);
        Integer testPlanId = testPlan.getTestPlanId();
        Map map = Maps.newHashMap();
        map.put("testCaseIds", testCaseIds);
        map.put("testPlanId", testPlanId);
        testPlanMapper.addPlanDetail(map);

        if (!StringUtils.isBlank(testPlan.getWeekTimeList())) {
            List list = JSON.parseObject(testPlan.getWeekTimeList(), List.class);
            if (!CollectionUtils.isEmpty(list)) {
                ScheduleJob scheduleJob = new ScheduleJob();
                BeanUtils.copyProperties(testPlan, scheduleJob);
                quartzService.addQuartzJob(scheduleJob);
            }
        }
    }

    /**
     * 读取日志,根据记录的最后一次大小读取文件
     *
     * @param buildTestId
     * @param lastTimeFileSize
     * @return
     */
    public ReportLog runLog(Integer buildTestId, Long lastTimeFileSize) {
        ReportLog reportLog = new ReportLog();
        if (null != lastTimeFileSize) {
            ReportLogFileUtil reportLogFileUtil = new ReportLogFileUtil();
            reportLog = reportLogFileUtil.read(shareDir + File.separator + buildTestId + ".log", lastTimeFileSize);
        }
        return reportLog;
    }
}
